package com.lanyou.cook.service;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.xml.parsers.ParserConfigurationException;

import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleSecurityException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.kdr.KettleDatabaseRepository;
import org.pentaho.di.repository.kdr.KettleDatabaseRepositoryMeta;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xml.sax.SAXException;

import com.lanyou.cook.common.Constants;
import com.lanyou.cook.entity.kettle.KettleDataSource;
import com.lanyou.cook.repository.KettleDataSourceRepository;

@Service
public class KettleRepositoryService {

	@Autowired
	private KettleDataSourceRepository kettleDataSourceRepository;
	
	private KettleDatabaseRepositoryMeta databaseRepositoryMeta;
	
	@PostConstruct
	private void init() throws ParserConfigurationException, SAXException, IOException, KettleSecurityException, KettleException{
		// 初始化kettle环境
		KettleEnvironment.init();
		
		// 初始化数据库型资源库的元信息
		databaseRepositoryMeta = buildDatabaseRepositoryMeta();
	}
	
	private KettleDatabaseRepositoryMeta buildDatabaseRepositoryMeta() throws ParserConfigurationException, SAXException, IOException, KettleXMLException {

		KettleDataSource kettleRepositoryDataSource = kettleDataSourceRepository.findByName(Constants.KETTLE_DEAFAULT_REPOSITORY_CONNECTION_NAME_IN_R_DATABASE);
		
		DatabaseMeta dataMeta = new DatabaseMeta();
		dataMeta.setName(kettleRepositoryDataSource.getName());
		dataMeta.setDatabaseType(kettleRepositoryDataSource.getDataBaseTypeCode());
		dataMeta.setHostname(kettleRepositoryDataSource.getHostName());
		dataMeta.setDBPort(String.valueOf(kettleRepositoryDataSource.getPort()));
		dataMeta.setDBName(kettleRepositoryDataSource.getDatabaseName());
		dataMeta.setUsername(kettleRepositoryDataSource.getUsername());
		// 密码需解密
		dataMeta.setPassword(kettleRepositoryDataSource.getPassword());
		
		KettleDatabaseRepositoryMeta kettleDatabaseMeta = new KettleDatabaseRepositoryMeta();
		kettleDatabaseMeta.setConnection(dataMeta);
		return kettleDatabaseMeta;
	}
	
	public Repository buildRepository(){
		// 创建资源库对象，此时的对象还是一个空对象
		KettleDatabaseRepository repository = new KettleDatabaseRepository();
		// 给资源库赋值
		repository.init(databaseRepositoryMeta);
		return repository;
	}
	
}
